<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryObj.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="listTree"
          node-key="id"
          :data="list"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="hChange"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <!-- 路由跳转 -->
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>

          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <!-- 父组件需要监听上传成功的事件 -->
          <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="loadEmployment" />

          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employList">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <!-- 头像 -->
            <template v-slot="{row}">
              <img v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" class="user-avatar">
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">

            <template v-slot="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>

              <el-button size="mini" type="text" @click="role(row.id)">角色</el-button>
              <assign-role ref="myChild" :show-assign.sync="showAssign" :cur-id="curId" />

              <!-- 气泡框 -->
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="del(row.id)">
                <!-- @onConfirm点击确认按钮时触发 -->
                <el-button slot="reference" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>

          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">

          <el-pagination
            :current-page="queryObj.page"
            :page-sizes="[5, 10, 15]"
            :page-size="queryObj.pagesize"
            layout="sizes, prev, pager, next"
            :total="total"
            @current-change="changePage"
          />
        </el-row>
        <!-- 分页 -->
      </div>
    </div>
  </div>
</template>

<script>
import ImportExcel from './components/import-excel.vue'
import FileSaver from 'file-saver'
import { getEmployment, exportEmployee, delEmplyee } from '@/api/emplyee'
import { getDepartment } from '@/api/department'
import { arr2tree } from '@/utils'
import AssignRole from './components/assignRole.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel,
    AssignRole
  },
  data() {
    return {
      list: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      queryObj: {
        page: 1,
        pagesize: 10,
        keyword: null, // 模糊搜索字段
        departmentId: null
      },
      employList: [], // 员工列表
      total: 0,
      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      showAssign: false, // 分配角色的弹框
      curId: 0
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 获取部门列表
    async getDepartment() {
      const res = await getDepartment()
      // console.log(res.data)
      this.list = arr2tree(res.data, 0)

      // 第一个节点
      const id = this.list[0].id
      // console.log(id)//1
      this.$nextTick(() => {
        this.$refs.listTree.setCurrentKey(id)
        // setCurrentKey通过 key 设置某个节点的当前选中状态
      })
      // 重发请求
      this.loadEmployment()
    },
    // 获取员工列表
    async loadEmployment() {
      const res = await getEmployment(this.queryObj)
      // console.log(res.data.rows)
      this.employList = res.data.rows
      this.total = res.data.total
    },
    // 当前选中节点变化时触发的事件
    hChange(data) {
      // 切换部门时，查询第一页数据
      // console.log(data)
      // 重新记录id
      this.queryObj.departmentId = data.id
      this.queryObj.page = 1 // 设置第一页
      // 发请求拿到对应的员工列表
      this.loadEmployment()
    },
    // 分页器
    changePage(page) {
      // console.log(`当前页: ${page}`)
      // 1.更新页码
      this.queryObj.page = page
      // 2.重发请求
      this.loadEmployment()
    },
    // 模糊搜索
    changeValue() {
      // 单位时间内只执行最后一次 防抖
      clearTimeout(this.timer)// 清理上一次的定时器
      this.timer = setTimeout(() => {
        this.queryObj.page = 1
        this.loadEmployment()
      }, 300)
    },
    // 导出
    async exportEmployee() {
      // 调用导出接口
      const res = await exportEmployee()
      // FileSaver.saveAs(blob对象,文件名称)
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    // 删除
    async del(id) {
      // 1.获取id
      console.log(id)
      // 2.调接口
      await delEmplyee(id)
      if (this.list.length === 1) {
        if (this.page > 1) { this.page-- }
      }
      // 如果是当前页的最后一条数据,要向前翻一页
      // 3.重新刷新页面
      this.loadEmployment()
    },
    // 角色弹框
    role(id) {
      this.curId = id
      this.showAssign = true

      this.$nextTick(() => {
        this.$refs.myChild.roleDetail()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .user-avatar {
          cursor: pointer;
          width: 40px;
          height: 40px;
          border-radius: 10px;
          margin-right: 5px;
        }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
